﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using KL.Store.Core;
using KL.Store.Core.Domain;
using KL.Store.Core.Localization;
using KL.Store.Data;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using Microsoft.WindowsAzure.ServiceRuntime;

namespace KL.Store.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            
            #region Parameters.dsnStore

            Parameters.RoleEnvironment = RoleEnvironment.IsAvailable;

            if (Parameters.RoleEnvironment)
            {
                Parameters.InstanceId = RoleEnvironment.CurrentRoleInstance.Id;
                if (RoleEnvironment.GetConfigurationSettingValue("dsnStore") != null)
                {
                    Parameters.dsnStore = RoleEnvironment.GetConfigurationSettingValue("dsnStore");
                }
                else
                {
                    Parameters.dsnStore = "Can not read connection string from service configuration file!";
                }
            }
            else
            {
                if (System.Configuration.ConfigurationManager.AppSettings["dsnStore"] != null)
                {
                    Parameters.dsnStore = System.Configuration.ConfigurationManager.AppSettings["dsnStore"];
                }
                else
                {
                    Parameters.dsnStore = "Can not read connection string from configuration file!";
                }
            }

            #endregion

            dbParameters.dsnStore = Parameters.dsnStore;

            Current.LM = dbLocalization.GetList();

            #region RefreshSiteParameters

            while (!dbRefs.RefreshSiteParameters())
            {
                Logger.Write("Parametreler Güncellenemedi!!!, Servis Başlatılamadı, Tekrar Parametre Güncellemesi Deneniyor", "Trace");
            }
            Logger.Write("Servis Başladı, Parametreler Güncellendi", "Trace");

            #endregion

            var cacheManager = CacheFactory.GetCacheManager("Cache Manager");
            cacheManager.Add("ParameterLastUpdateDate", Parameters.ParameterLastUpdateDate, CacheItemPriority.High, new CheckParameterUpdate(), new AbsoluteTime(DateTime.Now.AddMinutes(Parameters.ParameterCheckInterval)));

            #region Service Started Email Message

            if (!string.IsNullOrEmpty(Parameters.ErrorMessageToAddress))
            {
                try
                {
                    Utils.SendMail(Parameters.ErrorMessageToAddress, "", "", "Bilgi : IIS Servisi Başladı, Instance:" + Parameters.InstanceId, "Bilgi : IIS Servisi Başladı, Instance:" + Parameters.InstanceId, false);
                }
                catch { }
            }

            #endregion
        }

        public class CheckParameterUpdate : ICacheItemRefreshAction
        {
            public void Refresh(string removedKey, object expiredValue, CacheItemRemovedReason removalReason)
            {
                DateTime dbRefreshTime = Parameters.ParameterLastUpdateDate;

                #region Read db For Last Parameter Update Time

                try
                {
                    dbRefreshTime = dbRefs.GetRef2Old(1100);
                }
                catch (Exception ex)
                {
                    Logger.Write("Parametre Son Güncelleme Zamanı Veritabanından Okunamadı! ->" + ex.Message, "Exception");
                    try
                    {
                        if (!string.IsNullOrEmpty(Parameters.ErrorMessageToAddress))
                        {
                            Utils.SendMail(Parameters.ErrorMessageToAddress, "", "", "Parametre Son Güncelleme Zamanı Veritabanından Okunamadı!, Instance:" + Parameters.InstanceId, ex.Message, false);
                        }
                    }
                    catch { }
                }

                #endregion

                var cacheManager = CacheFactory.GetCacheManager("Cache Manager");

                if (Parameters.ParameterLastUpdateDate < dbRefreshTime)
                {
                    #region Update Parameters

                    try
                    {
                        //Parameters.ParameterLastUpdateDate updated in RefreshSiteParameters method below !!!
                        dbRefs.RefreshSiteParameters();

                        Logger.Write("Parametreler Güncellendi", "Trace");
                    }
                    catch (Exception ex)
                    {
                        Logger.Write("Parametreler Güncellenemedi! ->" + ex.Message, "Exception");
                        try
                        {
                            if (!string.IsNullOrEmpty(Parameters.ErrorMessageToAddress))
                            {
                                Utils.SendMail(Parameters.ErrorMessageToAddress, "", "", "Parametre Güncelleme İşlemi Sırasında Hata Alındı, Instance:" + Parameters.InstanceId, ex.Message, false);
                            }
                        }
                        catch { }
                    }

                    #endregion
                }

                #region Refresh Cache

                cacheManager.Add("ParameterLastUpdateDate", Parameters.ParameterLastUpdateDate, CacheItemPriority.High, new CheckParameterUpdate(), new AbsoluteTime(DateTime.Now.AddMinutes(Parameters.ParameterCheckInterval)));

                #endregion
            }
        }

    }
}